package com.mars.weixin.web.weixin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.utils.IpHelper;
import com.mars.base.common.utils.RandomUitl;
import com.mars.base.common.utils.security.SecurityUtils;
import com.mars.base.common.utils.web.ResponseResult;
import com.mars.base.web.BaseController;
import com.mars.weixin.common.WeixinConstant;
import com.mars.weixin.common.WeixinContext;

/**
 * 微信JS-SDK
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping(value="/weixin")
public class WeixinJSSdkController extends BaseController {

	/**
	 * JS-SDK Config 参数配置
	 * @param request
	 * @param response
	 */
	@PostMapping(value="/js/config")
	public Object config(HttpServletRequest request, HttpServletResponse response) {
		try {
			String appId = WeixinConstant.APPID ;
			String jsapi_ticket = WeixinContext.getJsApiTicket() ;
			String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10) ;
			String noncestr = RandomUitl.generateString(16) ;
			String url = request.getParameter("url") ;
			
			Map<String, Object> configMap = new HashMap<String, Object>() ;
			configMap.put("jsapi_ticket", jsapi_ticket) ;
			configMap.put("noncestr", noncestr) ;
			configMap.put("timestamp", timestamp) ;
			configMap.put("url", url) ;
			
			String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url ;
			
			String signature = SecurityUtils.sha1(str);  
			
			configMap.put("signature", signature) ;
			configMap.put("appid", appId) ;
			
			logger.debug("访问IP：[{}]，JSSDK配置参数：{}", IpHelper.getIpAddr(request), JSON.toJSONString(configMap));
			
			return configMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseResult.failure();
	}
	

}
